//用户

/**
 * 编辑视图模型
 */
interface IUserDetailViewModel{
    /**
     * 编号
     */
    userId?: string;
    /**
     * 用户名
     */
    userName: string;
    /**
     * 车牌号
     */
    carCode: string;
    /**
     * 角色
     */
    roles?: string;
    /**
     * 实名头像
     */
    realHeadImage: string;
    /**
     * 实名头像状态
     */
    realHeadImageStatus:string;
    /**
     * 实名头像工具栏
     */
    realHeadImageTool:boolean;
    /**
     * 实名头像通过
     */
    clickOkPassState:boolean;
    /**
     * 实名头像不通过
     */
    clickRemovePassState:boolean;
    /**
     * 身份证
     */
    idCardImage:string;
    /**
     * 身份证状态
     */
    idCardImageSatus:string;
    /**
     * 身份证状态工具栏
     */
    idCardImageTool:boolean;
    /**
     * 身份证通过
     */
    clickIdCardOkPassState:boolean;
    /**
     * 身份证不通过
     */
    clickIdCardRemovePassState:boolean;
    /**
     * 驾驶证
     */
    drivingLicenseImage:string;
    /**
     * 驾驶证状态
     */
    drivingLicenseImageStatus:string;
    /**
     * 驾驶证状态工具栏
     */
    drivingLicenseImageTool:boolean;
    /**
     * 驾驶证通过
     */
    clickDrivingLicenseOkPassState:boolean;
    /**
     * 驾驶证不通过
     */
    clickDrivingLicenseRemovePassState:boolean;
    /**
     * 行驶证
     */
    vehicleLicenseImage:string;
    /**
     * 行驶证状态
     */
    vehicleLicenseImageStatus:string;
    /**
     * 行驶证工具栏
     */
    vehicleLicenseImageTool:boolean;
    /**
     * 行驶证通过
     */
    clickVehicleLicenseOkPassState:boolean;
    /**
     * 行驶证不通过
     */
    clickVehicleLicenseRemovePassState:boolean;
    /**
     * 说明
     */
    message:string;
    /**
     * 驾驶证状态提交
     */
    drivingLicenseCertificated: number;
    /**
     * 实名头像状态提交
     */
    realHeadImageCertificated: number;
    /**
     * 身份证提交
     */
    idCardCertificated: number;
    /**
     * 行驶证提交
     */
    vehicleLicenseCertificated: number;
    /**
     * 保存事件
     */
    click: () => void;
    /**
     * 通过的点击事件
     */
    clickOk: (statusValue:string) => void;
    /**
     * 表示通过样式
     */
    clickOkPass: (statusValue:string) => void;
    /**
     * 不允许通过的点击事件
     */
    clickRemove: (statusValue:string) => void;
    /**
     * 不允许通过样式
     */
    clickRemovePass: (status: string) => void;
}

/**
 * 模型视图
 */
interface IUserViewModel extends IBaseViewModel<IUserQueryTerms>{
    /**
     * 审核状态下拉
     */
    chekoutStateDropDown: Array<ValueListItemResponse>;
    /**
     * 角色下拉
     */
    rolesDropDown: Array<RolesListItemResponse>;
    /**
     * ui-grid控制
     */
    gridOptions: uiGrid.IGridOptionsOf<UserListItemResponse>;
    /**
     * 编辑视图
     */
    detail: IUserDetailViewModel;
    /**
     * 实名认证（编辑）
     */
    editUser: (user:UserListItemResponse) => void;
    /**
     * 启用
     */
    enableUser: (userId:string) => void;
    /**
     * 禁用
     */
    disableUser: (userId:string) => void;
    /**
     * 强制修改（跳转页面）
     */
    linkToUsersEdit: () => void; 

}

/**
 * 查询条件
 */
interface IUserQueryTerms{
    /**
     * 关键字
     */
    searchingKeyWord: string;
    /**
     * 车牌号
     */
    searchingCarCode: string;
    /**
     * 起始时间
     */
    searchingStartTime: Date;
    /**
     * 结束时间
     */
    searchingEndTime: Date;
    /**
     * 角色
     */
    searchingRoleId: string;
    /**
     * 实名认证状态
     */
    searchingState: number;
    /**
     * 缓存
     */
    useCache: boolean;
}

class UserController extends ListController<IUserViewModel,IUserQueryTerms>{
    gridApi: uiGrid.IGridApiOf<UserListItemResponse>;

    constructor($scope: IUserViewModel,private $state:angular.ui.IStateService, private userService: IUserService, private rolesService: IRolesService, private valueService: IValueService, $ngBootbox: BootboxService)
    {
        super($scope);
    }

    init(): void{
        super.init();
        this.$scope.editUser = this.showEditUserDialog;
        this.$scope.enableUser = this.showEnableUserDialog;
        this.$scope.disableUser = this.showDisableUserDialog; 

        this.queryTerms = {
            searchingKeyWord:"",
            searchingCarCode:"",
            searchingStartTime:moment("0001-01-01").toDate(),
            searchingEndTime:new Date(),
            searchingRoleId:"",
            searchingState:null,
            useCache:false
        };

        this.$scope.gridOptions = {
            enableSorting: false,
            useExternalPagination: true,
            useExternalSorting: true,
            enableColumnResizing: true,
            paginationPageSizes: [10,20,30],
            columnDefs: [
                {name: "序号", field: "index", enableColumnMenu: false},
                {name: "车牌号", field: "carNumber", enableColumnMenu: false},
                {name: "车型", field: "carType", enableColumnMenu: false},
                {name: "车长", field: "carLength", enableColumnMenu: false},
                {name: "用户名", field: "userName", enableColumnMenu: false},
                {name: "真实姓名",field: "realNameState",enableColumnMenu:false},
                {name: "实名认证状态",field: "realNameState",enableColumnMenu:false},
                {name: "实名申请时间", field:"certificationTime",enableColumnMenu: false},
                {name:"禁用",field:"isLockedOut",enableColumnMenu:false},
                {name:"角色",field:"roles",enableColumnMenu:false},
                {
                    name: "操作",
                    cellFilter: "checkmark",
                    cellTemplate: '<a data-toggle="modal" data-target="#myModal" class="fa fa-edit m-l-xs primary text-info" title="编辑" ng-click="grid.appScope.editUser(row.entity)"></a> <a class="fa fa-check-circle primary text-success" ng-click="grid.appScope.enableUser(row.entity.id)" title="启用" ng-hide="row.entity.isEnabled"></a> <a class="fa fa-minus-circle primary text-primary" ng-show="row.entity.isEnabled" title="禁用" ng-click="grid.appScope.disableUser(row.entity.id)"></a>',
                    enableColumnMenu: false
                }
            ],
            onRegisterApi: (gridApi) => {
                this.gridApi = gridApi;
                gridApi.pagination.on.paginationChanged(this.$scope, this.paginationChanged);
            }
        };
        this.query();
        this.loadChekoutStateDropDown();
        
    }

     loadData(queryTerms: IUserQueryTerms, skip:number, count:number): void {
        this.userService.getList(queryTerms.searchingKeyWord,queryTerms.searchingCarCode,queryTerms.searchingStartTime,queryTerms.searchingEndTime,queryTerms.searchingRoleId,queryTerms.searchingState,queryTerms.useCache,skip,count).then(result => {
            this.$scope.gridOptions.totalItems = result.data.total;
            this.$scope.gridOptions.data = result.data.list;
            
            if(skip == 0){
                this.$scope.gridOptions.paginationCurrentPage = 1;
            }
            this.$scope.querying = false;
        }, error => {
            this.$scope.querying = false;
        });
    }

    /**
     *加载审核状态 
     */
    loadChekoutStateDropDown(): void {
        this.$scope.chekoutStateDropDown = this.valueService.getCheckStateList().list;
    }
    /**
     * 加载角色
     */
    loadRolesDropDown(): void{
        this.rolesService.getList().then(result => {
            this.$scope.rolesDropDown = result.data.list;
        });
    }

    /**
     * 显示实名认证窗口（编辑）
     */
    showEditUserDialog(user: UserListItemResponse): void{
        this.userService.getDetail(user.userId).then(result =>{
            this.$scope.detail= {
                userId:user.userId,
                carCode:result.data.carCode,
                userName: user.realName || user.userName || user.phoneNumber,
                roles: user.roles,
                realHeadImageStatus: this.valueService.getCheckStateList().list[result.data.realHeadState].text,
                idCardImageSatus: this.valueService.getCheckStateList().list[result.data.idCardState].text,
                drivingLicenseImageStatus: this.valueService.getCheckStateList().list[result.data.drivingLincenseState].text,
                vehicleLicenseImageStatus:this.valueService.getCheckStateList().list[result.data.vehicleLicenseState].text,

                realHeadImage:result.data.realHeadImage,
                idCardImage:result.data.idCardImage,
                drivingLicenseImage:result.data.drivingLicenseImage,
                vehicleLicenseImage:result.data.vehicleLicenseImage,

                realHeadImageTool: result.data.realHeadState == 2 && result.data.realHeadImage !== null,
                idCardImageTool: result.data.idCardState == 2 && result.data.idCardImage !== null,
                drivingLicenseImageTool: result.data.drivingLincenseState == 2 && result.data.drivingLicenseImage !== null,
                vehicleLicenseImageTool: result.data.vehicleLicenseState == 2 && result.data.vehicleLicenseImage !==null,

                clickOkPassState:true,
                clickRemovePassState:true,

                clickIdCardOkPassState:true,
                clickIdCardRemovePassState:true,

                clickDrivingLicenseOkPassState:true,
                clickDrivingLicenseRemovePassState:true,

                clickVehicleLicenseOkPassState:true,
                clickVehicleLicenseRemovePassState:true,

                drivingLicenseCertificated:result.data.drivingLincenseState,
                realHeadImageCertificated:result.data.realHeadState,
                idCardCertificated:result.data.idCardState,
                vehicleLicenseCertificated:result.data.vehicleLicenseState,

                message: result.data.message,
                click: this.editUser,
                clickOk:this.clickOk,
                clickOkPass:this.clickOkPass,
                clickRemove:this.clickRemove,
                clickRemovePass:this.clickRemovePass
            };
        });
    }

    editUser():void{
        $ngBootbox.confirm("确定保存该数据吗？").then(e =>{
            this.userService.putUserRealNameCertificationStatus(
                this.$scope.detail.userId,
                this.$scope.detail.carCode,
                this.$scope.detail.drivingLicenseCertificated,
                this.$scope.detail.realHeadImageCertificated,
                this.$scope.detail.idCardCertificated,
                this.$scope.detail.vehicleLicenseCertificated
            ).then(result => {
                this.query();
                $('#myModal').modal('hide');
            })
        })
    }

    /**
     * 启用
     */
    showEnableUserDialog(userId: string): void{
        $ngBootbox.confirm("是否启用？").then(e => {
            this.userService.setAccountLockoutState(userId,false).then(result => {
                this.query();
            });
        });
    }
    /**
     * 禁用
     */
    showDisableUserDialog(userId: string): void{
        $ngBootbox.confirm("是否启用？").then(e => {
            this.userService.setAccountLockoutState(userId,true).then(result => {
                this.query();
            });
        });
    }
    /**
     * 跳转页面（强制修改）
     */
    linkToUsersEdit(): void{
        this.$state.go("app.management.user_edit", { userId: this.$scope.detail.userId, realName: this.$scope.detail.userName,  roles: this.$scope.detail.roles });
        $('#myModal').modal('hide');
    }
    /**
     * 点击事件（认证通过）
     */
    clickOk(statusValue:string):any{
        this.statePassCheck('pass',statusValue,false);
    }
    /**
     * 认证通过后 样式
     */
    clickOkPass(statusValue: string): any{
        this.statePassCheck('pass',statusValue,true);
    }
    /**
     * 点击事件（认证不通过）
     */
    clickRemove(statusValue: string):any{
        this.statePassCheck('remove',statusValue, null, false);
    }
    /**
     * 认证不通过后 样式
     */
    clickRemovePass(statusValue: string):any{
        this.statePassCheck('remove',statusValue, null, true);
    }

    /**
     * 认状态函数
     */
    statePassCheck(way: string, statusValue:string , passValue?: boolean, dispassValue?: boolean):any{
       if(statusValue == 'RealHeadImage'){
           switch(way){
               case 'pass': return this.$scope.detail.clickOkPassState = passValue;
               case 'remove': return this.$scope.detail.clickRemovePassState = dispassValue;
           }
           this.$scope.detail.realHeadImageCertificated = this.getStateResult(this.$scope.detail.clickRemovePassState, this.$scope.detail.clickOkPassState);
       }else if(statusValue == 'IDCardImage'){
           switch(way){
               case 'pass': return this.$scope.detail.clickIdCardOkPassState = passValue;
               case 'remove': return this.$scope.detail.clickIdCardRemovePassState = dispassValue;
           }
             this.$scope.detail.idCardCertificated = this.getStateResult(this.$scope.detail.clickIdCardRemovePassState, this.$scope.detail.clickIdCardOkPassState);
       }else if(statusValue == 'DrivingLicenseImage'){
           switch(way){
               case 'pass': return this.$scope.detail.clickDrivingLicenseOkPassState = passValue;
               case 'remove': return this.$scope.detail.clickDrivingLicenseRemovePassState = dispassValue;
           }
           this.$scope.detail.drivingLicenseCertificated = this.getStateResult(this.$scope.detail.clickDrivingLicenseRemovePassState, this.$scope.detail.clickDrivingLicenseOkPassState);
       }else if(statusValue == 'vehicleLicenseImage'){
           switch(way){
               case 'pass': return this.$scope.detail.clickVehicleLicenseOkPassState = passValue;
               case'remove': return this.$scope.detail.clickVehicleLicenseRemovePassState = dispassValue;
           }
            this.$scope.detail.vehicleLicenseCertificated = this.getStateResult(this.$scope.detail.clickVehicleLicenseRemovePassState, this.$scope.detail.clickVehicleLicenseOkPassState);
       }                            
    }
    /**
     * 实名认证状态转换（提交数据）
     */
    getStateResult(clickRemovePassState:boolean,clickOkPassState:boolean): number{
        if (clickRemovePassState == true && clickOkPassState == true) {
            return 2;
        } else if (clickRemovePassState == false) {
            return 4;
        } else if (clickOkPassState == false) {
            return 3;
        }
    };
     
}

app.controller('userController',['$scope','userService','$ngBootbox', UserController]);